//
//  HttpUtil.m
//  NewsReader
//
//  Created by blacksun on 10-10-18.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "HttpUtil.h"
#import "NewsReaderAppDelegate.h"


@implementation HttpUtil

@synthesize currentConnection;
+(BOOL) isNetworkUseable{
	BOOL _isDataSourceAvailable = NO;
	Boolean success;  
	const char *host_name = "www.baidu.com";  
	SCNetworkReachabilityRef reachability =  SCNetworkReachabilityCreateWithName(NULL, host_name);  
	SCNetworkReachabilityFlags flags; 
	success = SCNetworkReachabilityGetFlags(reachability, &flags); 
	_isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) &&  !(flags & kSCNetworkFlagsConnectionRequired) 
								&& !(flags & kSCNetworkReachabilityFlagsInterventionRequired);  
	CFRelease(reachability);  
    return _isDataSourceAvailable;
	//return NO;
}

/*这样判断不准确，改用再主页测试，如果5秒内超时了，则认为是被墙了。
+(BOOL) isBaseUrlGFW{//判断GAE是否被墙
	BOOL isGFW = NO;
	Boolean success;  
	const char *host_name = [[URLAddress returnBaseUrl] UTF8String];  
	SCNetworkReachabilityRef reachability =  SCNetworkReachabilityCreateWithName(NULL, host_name);  
	SCNetworkReachabilityFlags flags;  
	success = SCNetworkReachabilityGetFlags(reachability, &flags);  
	isGFW = success && (flags & kSCNetworkFlagsReachable) &&  !(flags & kSCNetworkFlagsConnectionRequired);  
	CFRelease(reachability);  
    return !isGFW;//如果服务器可以连接，则表明没有被墙，所以取否
	
}*/


+ (void)showUsageAlertDialog
{
	NSString *message = @"网络不可用";
	UIAlertView *usageAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
	[usageAlertView show];
    
}

-(NSURLConnection *) performRequest:(NSURLRequest *)aRequest withTarget:(id)aTarget andCallBackAction:(SEL)aSelector isBackGround:(BOOL)isBackGround{
	//NSLog(@"need request");
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	if (!delegate.networkState) {
		[aTarget performSelectorOnMainThread:aSelector withObject:nil waitUntilDone:NO];
		NSLog(@"create");
		return nil;
	}
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
	[connection start];
	isConnectioning = YES;
	[NSTimer scheduledTimerWithTimeInterval:kRequestTimeOut target:self selector:@selector(connectionTimeOut) userInfo:nil repeats:NO];
	self.currentConnection = connection;
	[connection release];
	
	myTarget = aTarget;
	mySelector = aSelector;
	responseData = [[NSMutableData alloc] init];
	isBackground = isBackGround;
	return currentConnection;
}

-(void)loadNewFeedsWithSectionId:(NSString *)sectionId maxid:(NSInteger)maxid object:(id)target andSelector:(SEL) selector{
	myTarget = target;
	mySelector = selector;
	responseData = [[NSMutableData alloc] init];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	if ([SqlUtil countFeedsWithSectionId:sectionId from:maxid to:maxid+delegate.user.feedSizePerRequest]== delegate.user.feedSizePerRequest){
		NSArray *newFeeds = [SqlUtil selectFeedsWithSectionId:sectionId from:maxid to:maxid+delegate.user.feedSizePerRequest ];
		[myTarget performSelectorOnMainThread:mySelector withObject:newFeeds waitUntilDone:NO];
	}else {
		if (!delegate.networkState) {
			[myTarget performSelectorOnMainThread:mySelector withObject:nil waitUntilDone:NO];
			return;
		}
		
		NSString *urlStr = [URLAddress listFeedsWithSection:sectionId maxId:maxid];
		//NSLog(@"%@",urlStr);
		NSURL *url = [[NSURL alloc] initWithString:urlStr];
		NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
		[request addValue:@"gzip" forHTTPHeaderField:@"accept-encoding"];
		[request addValue:@"gzip,iPointReader" forHTTPHeaderField:@"user-agent"];
		NSURLConnection *connection =  [[NSURLConnection alloc] initWithRequest:request delegate:self];
		self.currentConnection = connection;
		isConnectioning = YES;
		[NSTimer scheduledTimerWithTimeInterval:kRequestTimeOut target:self selector:@selector(connectionTimeOut) userInfo:nil repeats:NO];
		[connection release];
		
		[request release];
		[url release];
	}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	//NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
	//NSLog(@"%d",[httpResponse statusCode]);
	[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	isConnectioning = NO;
	if (isBackground) {
		[myTarget performSelector:mySelector withObject:responseData];
	}else {
		[myTarget performSelectorOnMainThread:mySelector withObject:responseData waitUntilDone:NO];
	}
	self.currentConnection = nil;
	
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	isConnectioning = NO;
	//[error ]
	NSLog(@"errocode = %d",[error code]);
	self.currentConnection = nil;
}

-(void)connectionTimeOut{
	if (!isConnectioning) return;
	[self stopHttpConnection];
	[myTarget performSelectorOnMainThread:mySelector withObject:nil waitUntilDone:NO];
	
}
-(void)stopHttpConnection{
	isConnectioning = NO;
	[self.currentConnection cancel];
	self.currentConnection = nil;
	responseData = nil;
	
}

-(void) dealloc{
	[self.currentConnection release];
	[super dealloc];
}
@end
